<template>
  <div>
    <Row class="list_row" style="margin-top: 0px;min-height: 400px;">
      <Row style="margin: 5px 0px 10px 0px;">
        <Select v-model="selSoftType" :placeholder="$t('sysP.selectSoftT')" style="width: 200px;margin-right: 20px">
          <Option v-for="tc in allSoftTypeArr" :value="tc.val" :key="tc.val">{{tc.name}}</Option>
        </Select>
        <Input v-model="searchKeyword" :placeholder="$t('sysP.eVersione')" style="width: 200px;margin-right: 20px"/>
        <Button class="btnWhite" type="primary" icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
        <Button  class="btnWhite" type="primary" icon="md-add" @click="showAddModal"> {{$t('sysP.releaseV')}}</Button>
      </Row>
      <Table :columns="softVersionColumn" border :data="dataList" stripe :no-data-text="noDataMsg">
        <template slot-scope="{ row, index }" slot="seq">
          {{(currentPage - 1) * pageSize + index + 1}}
        </template>
        <template slot-scope="{ row, index }" slot="softType">
          <span v-if="row.softType == 'frontend'">{{$t('sysP.usefront') }}</span>
          <span v-if="row.softType == 'android_user'">{{$t('sysP.uAndroid')}}</span>
          <span v-if="row.softType == 'ios_user'">{{$t('sysP.useIos')}}</span>
        </template>

      </Table>
      <div class="div_page">
        <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
              show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
      </div>
    </Row>

    <!-- 查看弹窗 -->
    <Modal v-model="showModelVisiable" :mask-closable="false" width="850" :title="entityModelTitle">
      <Form ref="entityFormRef" :model="entityForm" :rules="addFormRules" :label-width="120">
        <FormItem :label="$t('sysP.softwareType')" prop="softType">
          <Select v-model="entityForm.softType" style="width: 200px;margin-right: 20px" @on-change="softTypeChg"
                  disabled>
            <Option v-for="tc in softTypeArr" :value="tc.val" :key="tc.val">{{tc.name}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('sysP.versionNum')" prop="versionNum">
          <Input v-model="entityForm.versionNum" :placeholder="$t('sysP.versionNum')" disabled></Input>
        </FormItem>
        <FormItem  :label="$t('sysP.formatVersion')" prop="formatVersion">
          <Input v-model="entityForm.formatVersion" :placeholder="$t('sysP.formatVersion')" disabled></Input>
        </FormItem>
        <FormItem    :label="$t('sysP.versionDesc')" prop="versionDesc">
          <Input v-model="entityForm.versionDesc" type="textarea" :autosize="{minRows: 2}"
                 :placeholder="$t('sysP.versionDesc')" disabled></Input>
        </FormItem>
        <FormItem :label="$t('sysP.installPage')" prop="versionDesc">
          <span style="font-size: 14px">{{ entityForm.fileName }}</span>
          <Button @click="downloadFile()" type="primary" style="margin-left: 10px">{{$t('sysP.downLoad')}}</Button>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="showModelVisiable=false">{{$t('cancel')}}</Button>
      </div>
    </Modal>

    <!-- 新增/修改版本弹窗 -->
    <Modal v-model="entityModelVisiable" :mask-closable="false" width="850" :title="entityModelTitle">
      <Form ref="entityFormRef" :model="entityForm" :rules="addFormRules" :label-width="120">
        <FormItem :label="$t('sysP.softwareType')" prop="softType">
          <Select v-model="entityForm.softType" style="width: 200px;margin-right: 20px" @on-change="softTypeChg">
            <Option v-for="tc in softTypeArr" :value="tc.val" :key="tc.val">{{tc.name}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('sysP.versionNum')" prop="versionNum">
          <Input v-model="entityForm.versionNum" :placeholder="$t('sysP.versionNum')"></Input>
        </FormItem>
        <FormItem :label="$t('sysP.formatVersion')" prop="formatVersion">
          <Input v-model="entityForm.formatVersion" :placeholder="$t('sysP.versionNum')"></Input>
        </FormItem>
        <FormItem  :label="$t('sysP.versionDesc')"  prop="versionDesc">
          <Input v-model="entityForm.versionDesc" type="textarea" :autosize="{minRows: 2}"
                  :placeholder="$t('sysP.versionDesc')"></Input>
        </FormItem>
        <FormItem  :label="$t('sysP.installPage')"  prop="filePath"
                  v-show="entityForm.softType == 'frontend' || entityForm.softType == 'android_user' ">
                  
          <Upload type="drag" name="softVersionFile" v-if="$i18n.locale==='zh-CN'" :action="uploadUrl" :headers="headers"
                  accept=".tar,.gz,.zip,.rar,.apk"
                  ref="versionFileUploader"
                  :on-success="uploadSuc" :on-error="uploadError" :before-upload="beforeUpload">
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>{{ uploadMsg }}</p>
            </div>
          </Upload>
          <Upload type="drag" name="softVersionFile" v-else :action="uploadUrlEn" :headers="headers"
                  accept=".tar,.gz,.zip,.rar,.apk"
                  ref="versionFileUploader"
                  :on-success="uploadSuc" :on-error="uploadError" :before-upload="beforeUpload">
            <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>{{ uploadMsg }}</p>
            </div>
          </Upload>
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: center">
        <Button @click="entityModelVisiable=false">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveOrUpdate" :loading="saveLoading" style="margin-left: 15px">
          <span v-if="!saveLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import SoftVersionApi from '@/api/softVersionApi'
import { isEmpty, copyObj, getToken } from '@/libs/util'

export default {
  data () {
    const validateVersionNumber = (rule, value, callback) => {
      const posIntReg = /^[1-9]\d*$/
      if (!(posIntReg.test(value))) {
        callback(new Error( this.$t('sysP.versionBz')))
      }
      callback()
    }
    return {
      showModelVisiable: false,
      // uploadMsg: '请上传zip/rar/tar/gz格式的安装包',
      uploadMsg:this.$t('sysP.apkZip') ,
      headers: {},
      formatFileArr: ['zip', 'rar', 'tar', 'gz','apk'],
      // formatFileArr: ['apk'],
      // uploadUrl: 'web/softVersion/uploadFile/frontend',
      uploadUrl: 'performance/web/softVersion/uploadFile/android_user',
      uploadUrlEn: 'performanceEng/web/softVersion/uploadFile/android_user',
      saveLoading: false,
      searchKeyword: '',
      noDataMsg:  this.$t('common.noData'),
      entityModelTitle: this.$t('sysP.addSoftV'),
      isCanChooseTc: false,
      selSoftType: 'all',
      allSoftTypeArr: [
        { 'name': this.$t('sysP.allSelectSoftT') , val: 'all' },
        { 'name': this.$t('sysP.usefront') , val: 'frontend' },
        { 'name': this.$t('sysP.uAndroid'), val: 'android_user' },
        { 'name': this.$t('sysP.useIos'), val: 'ios_user' }
      ],
      softTypeArr: [
        { 'name': this.$t('sysP.usefront'), val: 'frontend' },
        { 'name': this.$t('sysP.uAndroid'), val: 'android_user' },
        { 'name': this.$t('sysP.useIos'),  val: 'ios_user' }
      ],
      entityModelVisiable: false,
      entityForm: {
        id: '',
        softType: 'frontend',
        versionNum: '0',
        formatVersion: '',
        versionDesc: '',
        fileName: '',
        filePath: '',
        fileSize: 0,
        suffix: ''
      },
      addFormRules: {
        softType: [
          { required: true, message:  this.$t('sysP.softTypMust'), trigger: 'blur' }
        ],
        versionNum: [
          { required: true, message:  this.$t('sysP.iVersionMust'), trigger: 'blur' },
          { validator: validateVersionNumber, trigger: 'blur' }
        ],
        formatVersion: [
          { required: true, message:  this.$t('sysP.eVersionMust') , trigger: 'blur' },
          { type: 'string', max: 64, message: this.$t('common.namelenLow64Tips'), trigger: 'blur' }
        ],
        versionDesc: [
          { required: true, message:  this.$t('sysP.versionMust'), trigger: 'blur' },
          { type: 'string', max: 500, message:  this.$t('sysP.versionLow500'), trigger: 'blur' }
        ]
      },
      totalCount: 20,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      softVersionColumn: [
        {
         title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          
          title: this.$t('sysP.softwareType'), 
          slot: 'softType'
        },
        {
         title: this.$t('sysP.versionNum'), 
          key: 'versionNum'
        },
        {
            title: this.$t('sysP.formatVersion'), 
          key: 'formatVersion'
        },
        {
           title: this.$t('sysP.versionDesc'),  
          key: 'versionDesc'
        },
        {
           title: this.$t('common.createTime'), 
          key: 'createTime'
        },
        {
            title: this.$t('common.optColumn'), 
          key: 'action',
        width: 210,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnBlue',
                on: {
                  click: () => {
                    this.showViewModal(params.row)
                  }
                }
              }, this.$t('common.previewBtn') ),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small'
                },
                class: 'btnYellow',
                style: {
                  marginRight: '15px'
                },
                on: {
                  click: () => {
                    this.showEditModal(params.row)
                  }
                }
              }, this.$t('common.editBtn')),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                class: 'btnRed',
                on: {
                  click: () => {
                    this.del(params.row)
                  }
                }
              },  this.$t('common.deleteBtn'))
            ])
          }
        }]
    }
  },

  mounted () {
    this.headers = { 'sports-user-token': getToken() }
    this.search()
  },
  methods: {
    softTypeChg (val) {
      if (val == 'frontend') {
        // this.uploadMsg = '请上传使用前端安装包（zip/rar/tar/gz格式）'
        this.uploadMsg = this.$t('sysP.apkTips')
        this.uploadUrl = 'web/softVersion/uploadFile/android_user' 
        // 客户部署需要加上传接口前缀
        if (this.$i18n.locale === "zh-CN") {
          this.uploadUrl = 'performance/web/softVersion/uploadFile/android_user' 
        }else{
          this.uploadUrlEn = 'performanceEng/web/softVersion/uploadFile/android_user' 
        }
      } else if (val == 'android_user') {
        this.uploadMsg = this.$t('sysP.apkATips')
        this.uploadUrl = 'web/softVersion/uploadFile/' + val
         // 客户部署需要加上传接口前缀
        if (this.$i18n.locale === "zh-CN") {
          this.uploadUrl = 'performance/web/softVersion/uploadFile/' +val
        }else{
          this.uploadUrlEn = 'performanceEng/web/softVersion/uploadFile/' +val
        }
      }
    },
    beforeUpload (file) {
      if (this.$refs.versionFileUploader.fileList.length >= 1) {
        this.$Message.error(this.$t('sysP.onlyApk') )
        return false
      }
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (this.entityForm.softType == 'frontend' && !this.formatFileArr.includes(fileExt)) {
        // this.$Message.error('请上传zip/rar/tar/gz格式的安装包')
        this.$Message.error(this.$t('sysP.apkZip'))
        return false
      }
      if (this.entityForm.softType == 'android_user' && fileExt != 'apk') {
        this.$Message.error(this.$t('sysP.apkZip'))
        return false
      }
    },
    uploadSuc (response, file, fileList) {
      console.log('上传成功：' + JSON.stringify(response))
      const resp = response.data.data
      this.entityForm.fileName = resp.fileName
      this.entityForm.filePath = resp.filePath
      this.entityForm.fileSize = resp.fileSize
      this.entityForm.suffix = resp.suffix
      console.log('当前数据：' + JSON.stringify(this.entityForm))
      this.$Message.success(this.$t('sysP.uploadSuc') )
    },
    uploadError (error, file, fileList) {
      console.log('上传失败：' + file.msg)
      this.$Message.error( this.$t('sysP.uploadFail') + file.msg)
    },
    search () {
      this.currentPage = 1
      this.fetchDataList()
    },
    fetchDataList () {
      this.noDataMsg =  this.$t('common.loading')
      this.dataList = []
      var param = { 'pageSize': this.pageSize, 'currentPage': this.currentPage }
      if (this.searchKeyword.length > 0) {
        param.formatVersion = this.searchKeyword
      }
      if (this.selSoftType != 'all') {
        param.softType = this.selSoftType
      }
      SoftVersionApi.pageResult(param).then(res => {
        this.dataList = res.data.data.pageResult.items
        this.totalCount = res.data.data.pageResult.totalCount
        this.noDataMsg =  this.$t('common.noData')
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    showAddModal () {
      this.$refs.entityFormRef.resetFields()
      this.entityForm = {
        id: '',
        softType: 'frontend',
        versionNum: '0',
        formatVersion: '',
        versionDesc: '',
        fileName: '',
        filePath: '',
        fileSize: 0,
        suffix: ''
      }
      this.entityModelTitle =  this.$t('sysP.releaseV')
      this.entityModelVisiable = true
      this.$refs.versionFileUploader.fileList = []
    },
    showViewModal (row) {
      this.entityModelTitle =  this.$t('sysP.vVinfo')
      this.entityForm = copyObj(row)
      this.showModelVisiable = true
    },
    showEditModal (row) {
      this.$refs.entityFormRef.resetFields()
      this.entityModelVisiable = true
      this.entityModelTitle =  this.$t('sysP.editVInfo')
      this.entityForm = copyObj(row)
      this.entityForm.versionNum = row.versionNum + ''
      // 文件
      this.$refs.versionFileUploader.fileList = [
        {
          name: this.entityForm.fileName,
          percentage: 100,
          showProgress: true,
          size: this.entityForm.fileSize,
          status: 'finished',
          uid: 1,
          url: 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar'
        }
      ]
    },
    saveOrUpdate () {
      this.$refs.entityFormRef.validate((valid) => {
        if (valid) {
          if (this.entityForm.softType == 'frontend' || this.entityForm.softType == 'android_user') {
            if (this.entityForm.fileName.length == 0) {
              this.$Message.warning(this.$t('sysP.apkZip'))
              return
            }
          }
          this.saveLoading = true
          SoftVersionApi.saveOrUpdate(this.entityForm).then(response => {
            this.saveLoading = false
            if (this.entityForm.id == '') {
              this.$Message.success(this.$t('sysP.vVsuc') )
            } else {
              this.$Message.success(this.$t('sysP.vESuc') )
            }
            this.$refs.entityFormRef.resetFields()
            this.entityModelVisiable = false
            this.fetchDataList()
          }, error => {
            this.saveLoading = false
            this.$Message.error(error.response.data.msg)
          })
        }
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchDataList()
    },
    del (row) {
      this.$Modal.confirm({
    title: this.$t('common.dDeleteTitleConfirm'),
        content: this.$t('common.DdeleteCt'),
        okText: this.$t('common.deleteBtn'),
        cancelText: this.$t('cancel'),
        onOk: () => {
          this.doDel(row.id)
        }
      })
    },
    doDel (id) {
      SoftVersionApi.delete(id).then(res => {
      this.$Message.success(this.$t('common.deleteSuc'))
        this.fetchDataList()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    downloadFile () {
      window.open('api/v1/version/_download/' + this.entityForm.id)
    }
  }
}
</script>
